package com.it.gateway.filter;



import com.it.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * JWT认证过滤器
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Value("${jwt.token.header}")
    private String tokenHeader;

    @Value("${secure.ignore.urls}")
    private List<String> ignoreUrls;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        
        // 检查是否为不需要token的URL
        if (isIgnoreUrl(path)) {
            return chain.filter(exchange);
        }
        
        // 获取token
        String token = request.getHeaders().getFirst(tokenHeader);
        
        // 如果没有token，从请求参数中获取
        if (StringUtils.isBlank(token)) {
            token = request.getQueryParams().getFirst("token");
        }
        
        // 验证token
        if (StringUtils.isBlank(token) || !JwtUtils.validateToken(token)) {
            return unauthorized(exchange);
        }
        
        // 将用户ID添加到请求头中
        Long userId = JwtUtils.getUserIdFromToken(token);
        if (userId != null) {
            ServerHttpRequest newRequest = request.mutate()
                    .header("userId", String.valueOf(userId))
                    .build();
            return chain.filter(exchange.mutate().request(newRequest).build());
        }
        
        return chain.filter(exchange);
    }

    /**
     * 判断是否为忽略的URL
     */
    private boolean isIgnoreUrl(String path) {
        return ignoreUrls.stream().anyMatch(url -> antPathMatcher.match(url, path));
    }

    /**
     * 响应未授权错误
     */
    private Mono<Void> unauthorized(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        
        String result = "{\"code\":\"401\",\"message\":\"未授权，请登录\",\"success\":false}";
        DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return -100; // 设置过滤器的优先级，数字越小优先级越高
    }
} 